package com.candy.control;

import com.candy.config.ConstantProperties;
import com.candy.tools.AliyunOSSUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@RestController
@RequestMapping("upload")
public class UploadController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 文件上传
     * @param file
     */
    @RequestMapping(value = "uploadBlog",method = RequestMethod.POST)
    public String uploadBlog(MultipartFile file){
        String imgUrl=null;
        String endpoint= ConstantProperties.JAVA4ALL_END_POINT;
        String bucketName=ConstantProperties.JAVA4ALL_BUCKET_NAME1;
        imgUrl="https://"+bucketName+"."+endpoint+"/";


        logger.info("============>文件上传");
        try {

            if(null != file){
                String filename = file.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.upload(newFile);
                    imgUrl=imgUrl+uploadUrl;

                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return imgUrl;
    }

//    @RequestMapping(value = "toUploadBlog",method = RequestMethod.GET)
//    public String toUploadBlog(){
//        return "upload";
//    }

}